# -*- coding: UTF-8 -*-
# 2023/11/30 20:49
from threading import Thread

from ttkbootstrap import Checkbutton, BooleanVar
from ttkbootstrap.scrolled import ScrolledFrame

from computer.double_clicked_top import double_clicked_top
from computer.pool_download_preview_img import pool_download_preview_img
from tools.get_configer import my_configer
from tools.get_logger import get_logger

configer = my_configer()
loger = get_logger()


class class_page_frame(ScrolledFrame):
    def __init__(self, line_num, img_url_save_path_list, **kwargs):
        super().__init__(**kwargs)

        self.master = kwargs["master"]
        self.line_num = line_num
        self.img_tag_id_urls_list = img_url_save_path_list

        """
        [
        {
            "img_tag": f"{img_info['utag']}_{img_info['class_id']}_{img_info['id']}".replace(" ", "_"),
            "img_id": f"{img_info['class_id']}_{img_info['id']}",
            "url_key_list":["img_1600_900",...],
            "img_url": {
                f"img_{img_info['resolution']}": img_info["url"],
                "img_1600_900": img_info["img_1600_900"],
                "img_1440_900": img_info["img_1440_900"],
                "img_1366_768": img_info["img_1366_768"],
                "img_1280_800": img_info["img_1280_800"],
                "img_1280_1024": img_info["img_1280_1024"],
                "img_1024_768": img_info["img_1024_768"]
            },...
            {
            }
        ]
        """

        self.class_page_btn_list = list()  # 生成的所有按钮
        self.btn_variable_list = list()  # 生成的所有按钮

        self.add_img_class()

    def add_img_class(self):
        """
        以按钮图片形式添加图片到ScrolledFrame中
        """
        row = 0
        for column in range(len(self.img_tag_id_urls_list)):
            img_tag_id_urls_dict = self.img_tag_id_urls_list[column]

            # 创建组件并给组件添加img_id、img_url、save_path属性方便后面异步使用
            btn_variable = BooleanVar()
            check_btn = Checkbutton(self, variable=btn_variable)

            # 绑定属性方便线程池调用
            setattr(check_btn, "variable", btn_variable)
            setattr(check_btn, "img_tag_id_urls_dict", img_tag_id_urls_dict)

            setattr(btn_variable, "img_tag_id_urls_dict", img_tag_id_urls_dict)

            # 设置双击预览
            check_btn.bind("<Double-Button-1>", self.double_clicked)

            # 布局和拉伸策略
            if column % self.line_num == 0 and column != 0:
                row += 1
            check_btn.grid(row=row, column=column % self.line_num, ipadx=10, ipady=10)
            self.master.grid_rowconfigure(row, weight=1)
            self.master.grid_columnconfigure(column % self.line_num, weight=1)

            loger.info(f"批量生成多选按钮预览,按钮绑定信息:{img_tag_id_urls_dict}")

            # 把生成的按钮加入按钮列表
            self.class_page_btn_list.append(check_btn)
            self.btn_variable_list.append(btn_variable)

        thread_pool_download_thred = Thread(target=pool_download_preview_img, args=(self.class_page_btn_list,), daemon=True)
        thread_pool_download_thred.start()

    def double_clicked(self, event):
        """
        预览按钮双击回调
        """
        button = event.widget
        img_save_path = getattr(button, "save_path")
        img_tag = getattr(button, "img_tag_id_urls_dict")["img_tag"]
        double_clicked_top(img_save_path,
                           title=img_tag,  # 窗口标题
                           resizable=(False, False)  # 拉伸策略
                           )

    def get_select_btn(self):
        """
        获取当前所有已勾选的按钮列表
        """
        select_list = list()
        for btn_variable in self.btn_variable_list:
            select_state = btn_variable.get()
            img_tag_id_urls = getattr(btn_variable, "img_tag_id_urls_dict")
            img_tag = img_tag_id_urls["img_tag"]
            img_id = img_tag_id_urls["img_id"]
            img_urls_dict = img_tag_id_urls["img_url"]

            if select_state:
                select_list.append(img_tag_id_urls)
                loger.info(f"检查到选择信息,img_tag:{img_tag}, id:{img_id}, img_urls_dict:{img_urls_dict}")

        return select_list

    def get_all_btn(self):
        """
        获取当前所有已勾选的按钮列表
        """
        select_list = list()
        for btn_variable in self.btn_variable_list:
            img_tag_id_urls = getattr(btn_variable, "img_tag_id_urls_dict")
            select_list.append(img_tag_id_urls)

        return select_list
